package com.jh.user.service;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.AuthorizationHandle;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.TokenUtil;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.common.collect.ImmutableMap;
import com.jh.user.business.*;
import com.jh.user.pojo.*;
import com.jh.user.util.CommonsUtil;
import com.jh.user.util.ObjectUtils;
import com.jh.user.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.*;


@Controller
public class UserBankInfoService {

    private static final Logger LOG = LoggerFactory.getLogger(UserBankInfoService.class);

    @SuppressWarnings("unchecked")
    private static final Class<Map<String, Object>> MAP_CLASS = (Class<Map<String, Object>>)
            TypeFactory.defaultInstance().constructMapType(Map.class, String.class, Object.class).getRawClass();

    private final UserBankInfoBusiness userBankInfoBusiness;
    private final UserBankCardLimitBusiness userBankCardLimitBusiness;
    private final UserLoginRegisterBusiness userLoginRegisterBusiness;
    private final BrandManageBusiness brandMangeBusiness;
    private final RestTemplate restTemplate;

    final
    Util util;

    @Autowired
    public UserBankInfoService(
            UserBankInfoBusiness userBankInfoBusiness,
            UserBankCardLimitBusiness userBankCardLimitBusiness,
            UserLoginRegisterBusiness userLoginRegisterBusiness,
            BrandManageBusiness brandMangeBusiness,
            RestTemplate restTemplate, Util util) {
        this.userBankInfoBusiness = userBankInfoBusiness;
        this.userBankCardLimitBusiness = userBankCardLimitBusiness;
        this.userLoginRegisterBusiness = userLoginRegisterBusiness;
        this.brandMangeBusiness = brandMangeBusiness;
        this.restTemplate = restTemplate;
        this.util = util;
    }
    @Autowired
    private BankBranchBusiness bankBranchBusiness;

    /**
     * 根据银行卡号修改预留手机号
     *
     * @param request
     * @param cardNo
     * @param phone
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/update/bankphone")
    public @ResponseBody
    Object updateUserBankPhonebyCardno(HttpServletRequest request,
                                       @RequestParam(value = "cardNo") String cardNo,
                                       @RequestParam(value = "phone") String phone) {
        System.err.println(phone);
        System.err.println(cardNo);
        userBankInfoBusiness.updateUserBankPhonebyCardno(cardNo, phone);
        Map<String, Object> map = new HashMap<>();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "修改成功!");
        return map;
    }    //根据条件查询出bankName 李梦珂

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/payment/query/querysupportbanknamebyparams")
    public Object queryBankNameByUserIdAndCardNo(HttpServletRequest request,
                                                 @RequestParam(value = "user_id") long userId,
                                                 @RequestParam(value = "card_no") String cardNo,
                                                 @RequestParam(value = "type", defaultValue = "2") String type
    ) {

        Map map = new HashMap();
        UserBankInfo userbankinfo = null;

        userbankinfo = userBankInfoBusiness.queryBankNameByUserIdAndCardNo(userId, cardNo, type);
        if (userbankinfo != null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            map.put(CommonConstants.RESULT, userbankinfo);

        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "未查询到银行卡名称信息！");
        }

        return map;
    }


    /**
     * 根据银行卡号修改用户信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/update/cardno")
    public @ResponseBody
    void updateUserBankInfobyCardno(
            HttpServletRequest request,
            @RequestParam("province") String province,
            @RequestParam("city") String city,
            @RequestParam("bankBranchName") String bankBranchName,
            @RequestParam("bankBranchId") String lineNo,
            @RequestParam("securityCode") String securityCode,
            @RequestParam("expiredTime") String expiredTime,
            @RequestParam("bankno") String bankno
    ) {
        userBankInfoBusiness.updateUserBankInfoByCardno(bankBranchName, province, city, lineNo, securityCode, expiredTime, bankno);
    }

    //根据cardNo更改用户信息
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/update/bynewcardno")
    public @ResponseBody
    Object updateUserBankInfoByNewCarno(HttpServletRequest request,
                                        @RequestParam(value = "cardNo") String cardno,
                                        @RequestParam(value = "type", defaultValue = "2", required = false) String type,
                                        @RequestParam(value = "province", required = false) String province,
                                        @RequestParam(value = "city", required = false) String city,
                                        @RequestParam(value = "bankBranchName", required = false) String bankBranchName,
                                        @RequestParam(value = "lineNo", required = false) String lineNo,
                                        @RequestParam(value = "securityCode", required = false) String securityCode,
                                        @RequestParam(value = "expiredTime", required = false) String expiredTime) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            UserBankInfo bankInfo = userBankInfoBusiness.queryUserBankInfoByCardno(cardno, type);
            if (province == null) {
                bankInfo.setProvince(bankInfo.getProvince());
            } else {
                bankInfo.setProvince(province);
            }

            if (city == null) {
                bankInfo.setCity(bankInfo.getCity());
            } else {
                bankInfo.setCity(city);
            }

            if (bankBranchName == null) {
                bankInfo.setBankBranchName(bankInfo.getBankBranchName());
            } else {
                bankInfo.setBankBranchName(bankBranchName);
            }

            if (lineNo == null) {
                bankInfo.setLineNo(bankInfo.getLineNo());
            } else {
                bankInfo.setLineNo(lineNo);
            }

            if (securityCode == null) {
                bankInfo.setSecurityCode(bankInfo.getSecurityCode());
            } else {
                bankInfo.setSecurityCode(securityCode);
            }

            if (expiredTime == null) {
                bankInfo.setExpiredTime(bankInfo.getExpiredTime());
            } else {
                bankInfo.setExpiredTime(expiredTime);
            }
            userBankInfoBusiness.saveUserBankInfo(bankInfo);

            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "数据添加成功");
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "数据添加失败");
            LOG.info(e.getMessage());
        }
        return map;
    }

    /**
     * 根据用户的id获取用户的银行卡信息
     */
    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/user/bank/query/userid/{token}")
    public @ResponseBody
    Object queryBankInfoByUserid(HttpServletRequest request,
                                 @PathVariable("token") String token
    ) {

        Map<String, Object> map = new HashMap<>();
        String channelTag = "";
        String type = "";
        channelTag = request.getParameter("channel_tag");
        type = request.getParameter("type");
        long userId;
        long brandId;
        try {
            userId = TokenUtil.getUserId(token);
            brandId = TokenUtil.getBrandid(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }

        if ((StringUtils.isEmpty(channelTag) || "null".equals(channelTag)) && (StringUtils.isEmpty(type) || "null".equals(type))) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            map.put(CommonConstants.RESULT, userBankInfoBusiness.queryUserBankInfoByUserid(userId));
        } else {
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            String url = uri.toString() + "/v1.0/paymentchannel/pay/query/supportbank";
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("user_id", userId + "");
            requestEntity.add("brand_id", brandId + "");
            requestEntity.add("channel_tag", channelTag);
            requestEntity.add("type", type);
            String result = "";
            JSONArray resultObj = null;
            try {
                result = restTemplate.postForObject(url, requestEntity, String.class);
                JSONObject jsonObject = JSONObject.fromObject(result);

                if (!"000000".equals(jsonObject.getString("resp_code"))) {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                    map.put(CommonConstants.RESP_MESSAGE, jsonObject.containsKey(CommonConstants.RESP_MESSAGE) ? jsonObject.getString(CommonConstants.RESP_MESSAGE) : "亲,您绑定的卡暂不支持该通道哦!");
                    return map;
                }

                resultObj = jsonObject.getJSONArray("result");
            } catch (Exception e) {
                LOG.error("选择通道支持的银行卡出现空值======" + e.getMessage());
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "您未添加银行卡信息，请前往添加！！");
            }
            List<Map> listMap = new ArrayList<>();
            String oldstr = "\"";
            String newstr = "";
            int size = resultObj != null ? resultObj.size() : 0;
            for (int i = 0; i < size; i++) {
                Map<String, Object> map1 = new HashMap<>();
                JSONObject jsonObject2 = resultObj.getJSONObject(i);
                map1.put("id", jsonObject2.getString("id").replace(oldstr, newstr));
                map1.put("userId", jsonObject2.getString("userId").replace(oldstr, newstr));
                map1.put("bankBranchName", jsonObject2.getString("bankBranchName").replace(oldstr, newstr));
                map1.put("province", jsonObject2.getString("province").replace(oldstr, newstr));
                map1.put("city", jsonObject2.getString("city").replace(oldstr, newstr));
                map1.put("userName", jsonObject2.getString("userName").replace(oldstr, newstr));
                map1.put("bankName", jsonObject2.getString("bankName").replace(oldstr, newstr));
                map1.put("bankBrand", jsonObject2.getString("bankBrand").replace(oldstr, newstr));
                map1.put("cardNo", jsonObject2.getString("cardNo").replace(oldstr, newstr));
                map1.put("lineNo", jsonObject2.getString("lineNo").replace(oldstr, newstr));
                map1.put("securityCode", jsonObject2.getString("securityCode").replace(oldstr, newstr));
                map1.put("expiredTime", jsonObject2.getString("expiredTime").replace(oldstr, newstr));
                map1.put("phone", jsonObject2.getString("phone").replace(oldstr, newstr));
                map1.put("idcard", jsonObject2.getString("idcard").replace(oldstr, newstr));
                map1.put("cardType", jsonObject2.getString("cardType").replace(oldstr, newstr));
                map1.put("priOrPub", jsonObject2.getString("priOrPub").replace(oldstr, newstr));
                map1.put("nature", jsonObject2.getString("nature").replace(oldstr, newstr));
                map1.put("state", jsonObject2.getString("state").replace(oldstr, newstr));
                map1.put("idDef", jsonObject2.getString("idDef").replace(oldstr, newstr));
                map1.put("logo", jsonObject2.getString("logo").replace(oldstr, newstr));
                map1.put("type", jsonObject2.getString("type").replace(oldstr, newstr));
                map1.put("createTime", jsonObject2.getString("createTime").replace(oldstr, newstr));
                map1.put("useState", jsonObject2.getString("useState").replace(oldstr, newstr));
                listMap.add(map1);
            }
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            map.put(CommonConstants.RESULT, listMap);
        }

        return map;
    }

    /**
     * 根据用户的id获取用户的默认卡信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/default/userid")
    public @ResponseBody
    Object queryDefBankInfoByUserid(HttpServletRequest request,
                                    @RequestParam(value = "user_id") String userid) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserBankInfo model = userBankInfoBusiness.queryDefUserBankInfoByUserid(Long.parseLong(userid));
        if (model == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "无默认结算卡,请绑定默认结算卡");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        map.put(CommonConstants.RESULT, model);
        return map;
    }

    /**
     * 根据用户的id获取用户的银行卡信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/query/userid/type/{token}")
    public @ResponseBody
    Object queryBankInfoByUseridType(HttpServletRequest request,
                                     @PathVariable("token") String token,
                                     @RequestParam(value = "type") String type
    ) {
        Map<String, Object> map = new HashMap<String, Object>();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        map.put(CommonConstants.RESULT, userBankInfoBusiness.queryUserBankInfoByUserid(userId, type));
        return map;
    }


    /**
     * 根据用户的id获取用户的银行卡信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/query/useridandtype")
    public @ResponseBody
    Object queryBankInfoByUseridAndType(HttpServletRequest request,
                                        @RequestParam(value = "userId") String userId,
                                        @RequestParam(value = "type") String type
    ) {

        List<UserBankInfo> queryUserBankInfoByUserid = userBankInfoBusiness.queryUserBankInfoByUserid(Long.parseLong(userId), type);

        Map map = new HashMap();
        if (queryUserBankInfoByUserid != null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            map.put(CommonConstants.RESULT, queryUserBankInfoByUserid);
            return map;
        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "您未添加银行卡信息，请前往添加！！");
            return map;
        }

    }


    /**
     * 根据卡号信息获取用户提现的银行卡信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/query/cardno/{token}")
    public @ResponseBody
    Object queryBankInfoByCardno(@PathVariable("token") String token,
                                 @RequestParam(value = "type", defaultValue = "2", required = false) String type,
                                 @RequestParam(value = "cardno") String cardno) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            return CommonsUtil.returnSuccess(userBankInfoBusiness.queryUserBankInfoByCardno(cardno, type));
        } catch (Exception e) {
            LOG.error("UserBankInfoService.queryBankInfoByCardno, userId=======" + userId + "根据卡号信息获取用户提现的银行卡信息异常" + e.getMessage());
            return CommonsUtil.returnError("根据卡号信息获取用户提现的银行卡信息失败！");
        }

    }

    /**
     * 根据用户的id获取用户的默认提现卡信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/default/cardno")
    public @ResponseBody
    Object queryDefBankInfoByCardno(@RequestParam(value = "type", defaultValue = "2", required = false) String type,
                                    @RequestParam(value = "cardno") String cardno) {
        return CommonsUtil.returnSuccess(userBankInfoBusiness.queryUserBankInfoByCardno(cardno, type));
    }


    /**
     * 根据联行号信息获取用户的信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/query/lineno/{token}")
    public @ResponseBody
    Object queryBankInfoByLineno(@PathVariable("token") String token,
                                 @RequestParam(value = "lineno") String lineno) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            return CommonsUtil.returnSuccess(userBankInfoBusiness.queryUserBankInfoByLineno(lineno));
        } catch (Exception e) {
            LOG.error("UserBankInfoService.queryBankInfoByLineno, 根据联行号信息获取用户的信息失败" + ",userId====" + userId + "=====" + e);
            return CommonsUtil.returnError("根据联行号信息获取用户的信息失败！");
        }

    }

    /**
     * 查询用户是否是实名认证
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/auth")
    public @ResponseBody
    Object UserStatusAuth(@RequestParam("userId") long userId) {
        try {
            User user = userLoginRegisterBusiness.queryUserById(userId);
            if (!"1".equals(user.getRealnameStatus())) {
                return CommonsUtil.returnError("绑卡失败,请先进行实名认证!");
            } else {
                return CommonsUtil.returnSuccess("");
            }
        } catch (Exception e) {
            LOG.error("查询用户是否是实名认证" + ",userId====" + userId + "异常========" + e);
            return CommonsUtil.returnError("绑卡失败!");
        }
    }

    /**
     * 绑卡操作第一步：验证四要素，并返回分行/支行列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/query/{token}")
    public @ResponseBody
    Object queryBankInfo(@PathVariable("token") String token,
                       @RequestParam(value = "realname") String realname,
                       @RequestParam(value = "idcard") String idcard,
                       @RequestParam(value = "bankcard") String bankcard,
                       @RequestParam(value = "mobile") String mobile) {
        Map<String, Object> map = new HashMap<>();
        map.put("cardtype", "");
        map.put("bankBranches", "");
        realname = realname.trim();
        idcard = idcard.trim();
        bankcard = bankcard.trim();
        mobile = mobile.trim();
        if (StringUtils.isBlank(realname)
                || StringUtils.isBlank(idcard)
                || StringUtils.isBlank(bankcard)
                || StringUtils.isBlank(mobile)) {
            return CommonsUtil.returnError(CommonConstants.FALIED, "您输入的信息有误,请重新输入!");
        }

        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError(CommonConstants.ERROR_TOKEN, "token无效");
        }
        User user = userLoginRegisterBusiness.queryUserById(userId);
        if (!"1".equals(user.getRealnameStatus())) {
            return CommonsUtil.returnError(CommonConstants.FALIED, "绑卡失败,请先进行实名认证!");
        }

        /* 验证是否已绑定改银行卡 */
        UserBankInfo bandingBankCard = userBankInfoBusiness.isBandingBankCard(userId, bankcard);
        if (null != bandingBankCard) {
            return CommonsUtil.returnError("您已绑定该银行卡");
        }

        /* 验证是否绑定同一张卡 */
        int sameBindCardCount = userBankCardLimitBusiness.queryTodySameCount(userId, idcard, bankcard);
        if (sameBindCardCount >= 2) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "绑卡失败,相同卡号每天只能绑定2次,请明天再试!");
            JSONObject jsonObject = JSONObject.fromObject(map);
            return CommonsUtil.returnError("绑卡失败,相同卡号每天只能绑定2次,请明天再试!");
        }

        /* 每天绑卡总次数 */
        int erveyDayBindCardCount = userBankCardLimitBusiness.queryTodayCount(userId);
        if (erveyDayBindCardCount >= 5) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "绑卡失败,每人每天绑卡次数不能超过5次,请明天再试!");
            JSONObject jsonObject = JSONObject.fromObject(map);
            return CommonsUtil.returnError(jsonObject.toString(), "绑卡失败,每人每天绑卡次数不能超过5次,请明天再试!");
        }

        String bankAuth = "";
        String bankTag = "";
        String bankAscription = "";
        List<UserBrandJhKey> list = brandMangeBusiness.findByBrandIdAndKeyList(user.getBrandId());
        for (UserBrandJhKey jh :list) {
            //银行卡类型及真伪查询密钥
            if (jh.getKeyPlan().equalsIgnoreCase(CommonConstants.BANK_TAG))  bankTag = jh.getJhKey();
            //银行卡四元素校验密钥
            if (jh.getKeyPlan().equalsIgnoreCase(CommonConstants.BANK_AUTH)) bankAuth = jh.getJhKey();
            //银行卡归属地密钥
            if (jh.getKeyPlan().equalsIgnoreCase(CommonConstants.BANK_ASCRIPTION)) bankAscription = jh.getJhKey();
        }

        try {
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");

            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
            /* 查询银行卡归属地 */
            requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("cardid", bankcard);
            requestEntity.add("jhKey", bankAscription);
            requestEntity.add("jhUrl", CommonConstants.BANK_ASCRIPTION_URL);

            String url =  uri.toString() + "/v1.0/paymentchannel/bankcard/location";
            Map<String, Object> resultMap = restTemplate.postForObject(url, requestEntity, MAP_CLASS);

            LOG.info("/v1.0/paymentchannel/bankcard/location查询银行卡归属地resultMap：" + resultMap.toString());

            Object bankCard4Auth = resultMap.get("bankCard4Auth");
            JSONObject jsonObject = JSONObject.fromObject(bankCard4Auth);
            if (!jsonObject.containsKey("bankname")) {
                return CommonsUtil.returnError("获取银行卡归属地失败");
            }
            if (!jsonObject.containsKey("cardtype")){
                return CommonsUtil.returnError("获取银行卡类型失败");
            }

            String bankLocation = null == jsonObject.get("bankname") ? "" : jsonObject.get("bankname").toString();
            String cardtype = null == jsonObject.get("cardtype") ? "" : jsonObject.get("cardtype").toString();
            String province = null == jsonObject.get("province") ? "" : jsonObject.get("province").toString();
            String city = null == jsonObject.get("city") ? "" : jsonObject.get("city").toString();

            if (cardtype.contains("贷记卡") || cardtype.contains("信用卡")) {
                cardtype = CommonConstants.CREDIT_CARD;
            } else if (cardtype.contains("借记卡")) {
                cardtype = CommonConstants.DEBIT_CARD;
            } else {
                cardtype = CommonConstants.DEBIT_CARD;
            }
            map.put("cardtype", cardtype);

            LOG.info("jhKey = " + bankAscription);
            LOG.info("银行卡归属地bankLocation = " + bankLocation);
            LOG.info("银行卡归属地（省） = " + province);
            LOG.info("银行卡归属地（市） = " + city);

            /* 先验卡 */
            requestEntity.clear();
            requestEntity.add("realName", URLEncoder.encode(realname, "UTF-8"));
            requestEntity.add("idCard", idcard);
            requestEntity.add("bankCard", bankcard);
            requestEntity.add("mobile", mobile);
            requestEntity.add("bankTagKey", bankTag);
            requestEntity.add("bankTagUrl", CommonConstants.BANK_TAG_URL);
            requestEntity.add("bankAuthKey", bankAuth);
            requestEntity.add("bankAuthUrl", CommonConstants.BANK_AUTH_URL);

            url = uri.toString() + "/v1.0/paymentchannel/bankcard4/auth2";
            resultMap = restTemplate.postForObject(url, requestEntity, MAP_CLASS);

            LOG.info("验卡结果/v1.0/paymentchannel/bankcard4/auth2==resultMap = " + resultMap);

            Object authObj = resultMap.get("auth");
            Object locationObj = resultMap.get("location");
            Map<String, Object> authMap = ImmutableMap.of();
            Map<String, Object> locationMap = ImmutableMap.of();
            if (null == authObj) {
                LOG.info("信息不匹配,银行卡四要素验证失败, 用户输入信息: realName = {}, idCard = {}, bankCard = {}, mobile = {}", realname, idcard, bankcard, mobile);
                return CommonsUtil.returnError("银行卡四要素验证失败！");
            }
            if (authObj instanceof Map) {
                authMap = (Map<String, Object>) authObj;
            }
            if (locationObj instanceof Map) {
                locationMap = (Map<String, Object>) locationObj;
            }

            String lErrorCode = (String) locationMap.getOrDefault("errorCode", "2");
            if (!"0".equals(lErrorCode)) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_CARD_ERROR);
                String msg = (String) locationMap.getOrDefault("reason", "卡错误");
                map.put(CommonConstants.RESP_MESSAGE, msg);

                LOG.info("map=====" + map.toString());

                jsonObject = JSONObject.fromObject(map);
                return CommonsUtil.returnError(jsonObject.toString(), msg);
            }

            /* 卡验证有效 */
            int authResCode = (Integer) authMap.getOrDefault("resCode", 2);
            if (authResCode == 1) {
                /* 防止重复验卡*/
                if (!CommonConstants.CREDIT_0.equalsIgnoreCase(cardtype)) {
                    if (StringUtils.isBlank(bankLocation) || StringUtils.isBlank(province) || StringUtils.isBlank(city)) {
                        return CommonsUtil.returnError("获取银行卡归属地失败");
                    }
                }
                if (province.contains("省")) {
                    province = province.replaceAll("省", "");
                }
                if (city.contains("市")) {
                    city = city.replaceAll("市", "");
                }
                if (bankLocation.contains("信用社")) {
                    bankLocation = "信用";
                }

                Map<String, String> provinceAndCity = new HashMap<>();
                provinceAndCity.put("北京市", "北京");
                provinceAndCity.put("上海市", "上海");
                provinceAndCity.put("天津市", "天津");
                provinceAndCity.put("重庆市", "重庆");
                province = provinceAndCity.getOrDefault(province, province);
                city = provinceAndCity.getOrDefault(city, city);

                List<BankBranch> bankBranches = bankBranchBusiness.queryBankList(bankLocation, province, city);

                LOG.info("bankBranches：" + bankBranches.toString());

                if (!CommonConstants.CREDIT_CARD.equalsIgnoreCase(cardtype)) {
                    if (bankBranches.size() == 0) {
                        return CommonsUtil.returnError("获取银行列表失败");
                    }
                }

                map.put("bankBranches", bankBranches);

                LOG.info("绑卡操作四要素验证成功：" + map.toString());

                /** 新增一条绑卡记录 */
                UserBankCardLimit model = new UserBankCardLimit();
                model.setIdcard(idcard);
                model.setUserId(userId);
                model.setBankCard(bankcard);
                userBankCardLimitBusiness.save(model);
                JSONObject jsonObj = JSONObject.fromObject(map);
                return CommonsUtil.returnSuccess(jsonObj, "绑卡操作四要素验证成功");
            } else {
                String msg = (String) authMap.getOrDefault("message", "身份信息不匹配");
                return CommonsUtil.returnError(CommonConstants.ERROR_CARD_FAILED, msg);
            }
        } catch (Exception e) {
            LOG.error("UserBankInfoService.queryBankInfo绑卡操作第一步：验证四要素，并返回分行/支行列表");
            String errMsg = e.getLocalizedMessage() != null ? e.getLocalizedMessage() : e.getMessage();
            LOG.error("Unknown Exception: {}", errMsg);
            if (e.getCause() instanceof SQLException) {
                LOG.error("Unknown Exception: ", e);
            }
            return CommonsUtil.returnError("系统异常，请稍后再试！");
        }
    }

    @NotNull
    private String cardType(String cardtype) {
        if (cardtype.contains("贷记卡") || cardtype.contains("信用卡")) {
            cardtype = CommonConstants.CREDIT_0;
        } else if (cardtype.contains("借记卡")) {
            cardtype = CommonConstants.DEBIT_2;
        } else {
            cardtype = CommonConstants.DEBIT_2;
        }
        return cardtype;
    }

    /**
     * 绑定银行卡支行信息
     * @param token
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/addBank/{token}")
    public @ResponseBody Object addBank (
            @PathVariable("token") String token,
            @RequestParam(value = "realname") String realname,
            @RequestParam(value = "idcard") String idcard,
            @RequestParam(value = "bankcard") String bankcard,
            @RequestParam(value = "mobile") String mobile,
            @RequestParam(value = "type", defaultValue = "2", required = false) String type,
            @RequestParam(value = "expiretime", required = false) String expiretime,
            @RequestParam(value = "securitycode", required = false) String securitycode,
            @RequestParam(value = "bankName", required = false) String bankName,
            @RequestParam(value = "bankNo", required = false) String bankNo,
            @RequestParam(value = "topNo", required = false) String topNo,
            @RequestParam(value = "topName", required = false) String topName,
            MultipartFile bankCardPhoto) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            LOG.error("UserBankInfoService.addBank绑定银行卡支行信息异常，token无效");
            return CommonsUtil.returnError("token无效");
        }
        try {
            if (bankCardPhoto.isEmpty()) {
                return CommonsUtil.returnError("请上传银行卡正面图片！");
            }
            /* 信用卡 */
            if ("0".equalsIgnoreCase(type)) {
                if (StringUtils.isBlank(expiretime)) {
                    return CommonsUtil.returnError("请输入信用卡正面有效期！");
                }
                if (StringUtils.isBlank(securitycode)) {
                    return CommonsUtil.returnError("请输入信用卡背面安全码后三位！");
                }
            }

            User user = userLoginRegisterBusiness.queryUserById(userId);
            if (!"1".equals(user.getRealnameStatus())) {
                return CommonsUtil.returnError(CommonConstants.FALIED, "绑卡失败,请先进行实名认证!");
            }

            String bankAscription = "";
            List<UserBrandJhKey> list = brandMangeBusiness.findByBrandIdAndKeyList(user.getBrandId());
            for (UserBrandJhKey jh :list) {
                /* 银行卡归属地密钥 */
                if (jh.getKeyPlan().equalsIgnoreCase(CommonConstants.BANK_ASCRIPTION)) bankAscription = jh.getJhKey();
            }

            URI uri = util.getServiceUrl("paymentchannel", "error url request!");

            /* 查询银行卡归属地 */
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
            requestEntity.add("cardid", bankcard);
            requestEntity.add("jhKey", bankAscription);
            requestEntity.add("jhUrl", CommonConstants.BANK_ASCRIPTION_URL);

            String url =  uri.toString() + "/v1.0/paymentchannel/bankcard/location";
            Map<String, Object> resultMap = restTemplate.postForObject(url, requestEntity, MAP_CLASS);

            LOG.info("/v1.0/paymentchannel/bankcard/location查询银行卡归属地resultMap：" + resultMap.toString());

            Object bankCard4Auth = resultMap.get("bankCard4Auth");
            JSONObject bankLocationObj = JSONObject.fromObject(bankCard4Auth);
            if (StringUtils.isBlank(bankLocationObj.toString())) {
                return CommonsUtil.returnError("获取银行卡归属地错误，请重试！");
            }
            /* 银行卡归属地信息 */
            String bankLocation = null == bankLocationObj.get("bankLocation") ? "" : bankLocationObj.get("bankLocation").toString();
            String bankType = null == bankLocationObj.get("type") ? "" : bankLocationObj.get("type").toString();
            String logo = null == bankLocationObj.get("logo") ? "" : bankLocationObj.get("logo").toString();
            String nature = null == bankLocationObj.get("nature") ? "" : bankLocationObj.get("nature").toString();
            String bankname = null == bankLocationObj.get("bankname") ? "" : bankLocationObj.get("bankname").toString();
            String cardtype = null == bankLocationObj.get("cardtype") ? "" : bankLocationObj.get("cardtype").toString();//卡类型
            String city = null == bankLocationObj.get("city") ? "" : bankLocationObj.get("city").toString();
            String province = null == bankLocationObj.get("province") ? "" : bankLocationObj.get("province").toString();
            String abbreviation = null == bankLocationObj.get("abbreviation") ? "" : bankLocationObj.get("abbreviation").toString();

            cardtype = cardType(cardtype);

            /* 根据用户的id设置所有的卡都变成非默认*/
            userBankInfoBusiness.updateAllNoDefault(userId, type);

            Map<String, String> bankMap = new HashMap<>();
            bankMap.put("中国光大银行", "光大银行");
            bankMap.put("中国民生银行", "民生银行");
            bankMap.put("中国建设银行", "建设银行");
            bankMap.put("中国工商银行", "工商银行");
            bankMap.put("中国农业银行", "农业银行");
            bankMap.put("中国邮政储蓄银行", "邮政储蓄银行");
            bankMap.put("浦东发展银行", "浦发银行");
            bankMap.put("中国平安银行", "平安银行");
            bankMap.put("中国交通银行", "交通银行");

            if (StringUtils.isEmpty(bankNo)) {
                BankBranch bankBranch = userBankInfoBusiness.getBankBranchList(bankMap.getOrDefault(bankLocation, bankLocation));
                if (bankBranch != null) {
                    bankNo = bankBranch.getBankNo();
                }
            }

            //UserBankInfo userBankInfo = userBankInfoBusiness.queryUserBankInfoByCardno(bankcard, type);
            UserBankInfo userBankInfo = userBankInfoBusiness.getUserBankInfo(bankcard);
            if (null == userBankInfo) {
                /* 保存 */
                UserBankInfo bankInfo = new UserBankInfo();

                bankInfo.setUserId(userId);
                if ("2".equals(type)) {
                    bankInfo.setBankName(bankMap.getOrDefault(topName, bankLocation));
                } else {
                    bankInfo.setBankName(bankname);
                }
                bankInfo.setBankBrand("");
                bankInfo.setCardNo(bankcard);
                bankInfo.setUserName(realname);
                bankInfo.setNature(nature);
                bankInfo.setBankBranchName(bankName);
                bankInfo.setLineNo(StringUtils.trimToEmpty(bankNo));
                bankInfo.setBankAbbr(bankNo.substring(0, 3));
                bankInfo.setProvince(province);
                bankInfo.setCity(city);
                if ("0".equals(type)) {
                    bankInfo.setSecurityCode(securitycode);
                }
                bankInfo.setBillDay(0);
                bankInfo.setRepaymentDay(0);
                bankInfo.setCreditBlance(BigDecimal.ZERO);
                if (!StringUtils.isBlank(expiretime)) {
                    bankInfo.setExpiredTime(expiretime);
                }
                bankInfo.setPhone(mobile);
                bankInfo.setIdcard(idcard);
                bankInfo.setCardType(cardtype);
                bankInfo.setType(type);
                bankInfo.setState("0");
                bankInfo.setIdDef("1");
                bankInfo.setLogo(logo);
                bankInfo.setPriOrPub("0");
                bankInfo.setAbbreviation(abbreviation);
                bankInfo.setCreateTime(Calendar.getInstance().getTime());
//                bankInfo = userBankInfoBusiness.saveUserBankInfo(bankInfo);
                bankInfo = userBankInfoBusiness.addUserBankCardInfo(bankInfo, bankCardPhoto);
                bankInfo.transformCardType();
            } else {
                /* 更新 */
                userBankInfo.setUserId(userId);
                if ("2".equals(type)) {
                    userBankInfo.setBankName(bankMap.getOrDefault(topName, bankLocation));
                } else {
                    userBankInfo.setBankName(bankname);
                }
                userBankInfo.setBankBrand("");
                userBankInfo.setCardNo(bankcard);
                userBankInfo.setUserName(realname);
                userBankInfo.setNature(nature);
                userBankInfo.setBankBranchName(bankName);
                userBankInfo.setLineNo(StringUtils.trimToEmpty(bankNo));
                userBankInfo.setBankAbbr(bankNo.substring(0, 3));
                userBankInfo.setProvince(province);
                userBankInfo.setCity(city);
                if ("0".equals(type)) {
                    userBankInfo.setSecurityCode(securitycode);
                }
                userBankInfo.setBillDay(0);
                userBankInfo.setRepaymentDay(0);
                userBankInfo.setCreditBlance(BigDecimal.ZERO);
                if (!StringUtils.isBlank(expiretime)) {
                    userBankInfo.setExpiredTime(expiretime);
                }
                userBankInfo.setPhone(mobile);
                userBankInfo.setIdcard(idcard);
                userBankInfo.setCardType(cardtype);
                userBankInfo.setType(type);
                userBankInfo.setState("0");
                userBankInfo.setIdDef("1");
                userBankInfo.setLogo(logo);
                userBankInfo.setPriOrPub("0");
                userBankInfo.setAbbreviation(abbreviation);
//                userBankInfoBusiness.updateUserBankInfo(userBankInfo);
                userBankInfoBusiness.updateUserBankCardInfo(userBankInfo, bankCardPhoto);
            }

            return CommonsUtil.returnSuccess("绑定银行卡支行信息成功");
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e){
            LOG.error("UserBankInfoService.updateBank,更新银行卡支行信息" +  userId + "异常=======" + e.getMessage());
            e.printStackTrace();
            return CommonsUtil.returnError("系统异常，请稍后再试！");
        }
    }



//
//    /**
//     * 小磊
//     * 新增一张银行卡并且验卡
//     */
//    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/adds/{token}")
//    public @ResponseBody
//    Object addBankInfos(@PathVariable("token") String token,
//                        @RequestParam(value = "bankBranchName") String bankBranchName,
//                        @RequestParam(value = "realname") String realname,
//                        @RequestParam(value = "idcard") String idcard,
//                        @RequestParam(value = "bankcard") String bankcard,
//                        @RequestParam(value = "mobile") String mobile,
//                        @RequestParam(value = "type", defaultValue = "2", required = false) String type,
//                        @RequestParam(value = "expiretime", required = false) String expiretime,
//                        @RequestParam(value = "securitycode", required = false) String securitycode
//    ) {
//        Map<String, Object> map = new HashMap<>();
//        Map<String, String> bank = new HashMap<>();
//        bank.put("中国光大银行", "光大银行");
//        bank.put("中国民生银行", "民生银行");
//        bank.put("中国建设银行", "建设银行");
//        bank.put("中国工商银行", "工商银行");
//        bank.put("中国农业银行", "农业银行");
//        bank.put("中国邮政储蓄银行", "邮政储蓄银行");
//        bank.put("浦东发展银行", "浦发银行");
//        long userId;
//        try {
//            userId = TokenUtil.getUserId(token);
//        } catch (Exception e) {
//            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
//            map.put(CommonConstants.RESP_MESSAGE, "token无效");
//            return map;
//        }
//
//        int erveyDayBindCardCount = userBankCardLimitBusiness.queryTodayCount(userId);
//        int sameBindCardCount = userBankCardLimitBusiness.queryTodySameCount(userId, idcard, bankcard);
//        if (erveyDayBindCardCount >= 5) {
//            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
//            map.put(CommonConstants.RESP_MESSAGE, "绑卡失败,每人每天绑卡次数不能超过5次,请明天再试!");
//            return map;
//        }
//        if (sameBindCardCount >= 2) {
//            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
//            map.put(CommonConstants.RESP_MESSAGE, "绑卡失败,相同卡号每天只能绑定2次,请明天再试!");
//            return map;
//        }
//        UserBankCardLimit model = new UserBankCardLimit();
//        model.setIdcard(idcard);
//        model.setUserId(userId);
//        model.setBankCard(bankcard);
//        model = userBankCardLimitBusiness.save(model);
//        /**先验卡*/
//        URI uri = util.getServiceUrl("paymentchannel", "error url request!");
//        String url = uri.toString() + "/v1.0/paymentchannel/bankcard4/auth";
//
//
//        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
//        requestEntity.add("realname", realname);
//        requestEntity.add("idcard", idcard);
//        requestEntity.add("bankcard", bankcard);
//        requestEntity.add("mobile", mobile);
//
//
//        RestTemplate restTemplate = new RestTemplate();
//        String result = restTemplate.postForObject(url, requestEntity, String.class);
//        LOG.info("RESULT================" + result);
//        JSONObject jsonObject = JSONObject.fromObject(result);
//        JSONObject authObject = jsonObject.getJSONObject("auth");
//        JSONObject location = jsonObject.getJSONObject("location");
//
//        if (!location.getString("errorCode").equalsIgnoreCase("0")) {
//            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_CARD_ERROR);
//            map.put(CommonConstants.RESP_MESSAGE, location.getString("reason") != null && !location.getString("reason").equals("null") ? location.getString("reason") : "卡有误");
//            return map;
//        }
//        //查询号码归属地
//        uri = util.getServiceUrl("paymentchannel", "error url request!");
//        url = uri.toString() + "/v1.0/paymentchannel/bankcard/location";
//
//        requestEntity = new LinkedMultiValueMap<String, String>();
//        requestEntity.add("cardid", bankcard);
//        requestEntity.add("jhKey", idcard);
//
//        result = restTemplate.postForObject(url, requestEntity, String.class);
//        LOG.info("RESULT================" + result);
//        jsonObject = JSONObject.fromObject(result);
//        authObject = jsonObject.getJSONObject("auth");
//        location = jsonObject.getJSONObject("location");
//
//        /**卡验证有效 */
//        if (authObject.getInt("resCode") == 1) {
//            /***防止重复验卡*/
//
//            /**根据用户的id设置所有的开都变成非默认*/
//            userBankInfoBusiness.updateAllNoDefault(userId, type);
//            UserBankInfo userBankInfoTemp = userBankInfoBusiness.queryUserBankInfoByCardnoType(bankcard, type);
//            if (userBankInfoTemp != null && userBankInfoTemp.getCardNo() != null) {
//                LOG.info("银行验证有存在进入================");
//                userBankInfoTemp.setIdDef("1");
//                userBankInfoTemp.setState("0");
//                userBankInfoTemp = userBankInfoBusiness.saveUserBankInfo(userBankInfoTemp);
//            } else {
//                LOG.info("银行验证有不存在进入添加================");
//                UserBankInfo bankInfo = new UserBankInfo();
//                bankInfo.setCardNo(bankcard);
//                bankInfo.setExpiredTime(expiretime);
//                bankInfo.setSecurityCode(securitycode);
//                bankInfo.setCreateTime(new Date());
//                bankInfo.setPhone(mobile);
//                bankInfo.setUserId(userId);
//                bankInfo.setIdcard(idcard);
//                bankInfo.setUserName(realname);
//                bankInfo.setType(type);
//                bankInfo.setIdDef("1");
//                bankInfo.setState("0");
//                bankInfo.setCardType(location.getString("type"));
//                bankInfo.setBankBranchName(bankBranchName);
//
//                if (bank.containsKey(location.getString("bankLocation"))) {
//                    bankInfo.setBankName((String) bank.get(location.getString("bankLocation")));
//                } else {
//                    bankInfo.setBankName(location.getString("bankLocation"));
//                }
//                bankInfo.setNature(location.getString("nature"));
//                bankInfo.setLogo(location.getString("logo"));
//                userBankInfoTemp = userBankInfoBusiness.saveUserBankInfo(bankInfo);
//                LOG.info("银行验证有不存在进入添加================完毕");
//            }
//
//            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
//            map.put(CommonConstants.RESP_MESSAGE, "卡绑定成功");
//            map.put(CommonConstants.RESULT, userBankInfoTemp);
//            return map;
//        } else {
//            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_CARD_FAILED);
//            map.put(CommonConstants.RESP_MESSAGE, authObject.getString("message") != null && !authObject.getString("message").equals("null") ? authObject.getString("message") : "身份信息不匹配");
//            return map;
//        }
//    }


    /**
     * 删除一张银行卡
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/del/{token}")
    public @ResponseBody
    Object delBankInfo(@PathVariable("token") String token,
                       @RequestParam(value = "cardno") String cardno,
                       @RequestParam(value = "type", defaultValue = "2", required = false) String type) {
        Map map = new HashMap();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }

        UserBankInfo userBankInfo = userBankInfoBusiness.queryUserBankInfoByCardnoType(cardno, type);
        userBankInfo.setState("2");
        if (CommonConstants.DEBIT_CARD.equals(userBankInfo.getCardType())) {
            userBankInfo.setCardType(CommonConstants.DEBIT_2);
        }

        if (CommonConstants.CREDIT_CARD.equals(userBankInfo.getCardType())) {
            userBankInfo.setCardType(CommonConstants.CREDIT_0);
        }
        userBankInfoBusiness.saveUserBankInfo(userBankInfo);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "删除成功");
        return map;
    }


    /**
     * 设置一张默认结算卡
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/default/{token}")
    public @ResponseBody
    Object setDefaultBankInfo(@PathVariable("token") String token,
                              @RequestParam(value = "cardno") String cardno
    ) {
        Map map = new HashMap();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, userBankInfoBusiness.setDefaultBank(userId, cardno));
        map.put(CommonConstants.RESP_MESSAGE, "设置成功");
        return map;
    }

    /**
     * 根据银行名称获取银行编号
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/number/name")
    public @ResponseBody
    Object delBankNumber(@RequestParam(value = "bank_name") String bankName) {
        try {
            BankNumber bankNumber = userBankInfoBusiness.queryBankNumberByBankName(bankName);
            return CommonsUtil.returnSuccess(bankNumber);
        } catch (Exception e) {
            LOG.error("UserBankInfoService.delBankNumber, 根据银行名称获取银行编号异常=======" + e.getMessage());
            return CommonsUtil.returnError("根据银行名称获取银行编号失败！"+e.getMessage());
        }
    }

    /**
     * 根据银行名称获取银行编号
     * @param userId
     * @param idDef
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/query/bankInfo")
    public @ResponseBody Object queryBankInfo(@RequestParam(value = "userId") long userId,String idDef) {
        try {
            UserBankInfo bankInfo = userBankInfoBusiness.findUserBankInfoByUseridAndIdDef(userId,idDef,"2");
            return CommonsUtil.returnSuccess(bankInfo);
        } catch (Exception e) {
            LOG.error("UserBankInfoService.delBankNumber, 根据银行名称获取银行编号异常=======" + e.getMessage());
            return CommonsUtil.returnError("根据银行名称获取银行编号失败！"+e.getMessage());
        }
    }

    /**
     * 根据银行名称获取银行缩写
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/acronym/name")
    public @ResponseBody
    Object delBankAcronym(@RequestParam(value = "bank_name") String bankName) {
        try {
            BankAcronym bankAcronym = userBankInfoBusiness.queryBankAcronymByBankName(bankName);
            return CommonsUtil.returnSuccess(bankAcronym);
        } catch (Exception e) {
            LOG.error("UserBankInfoService.delBankAcronym, 根据银行名称获取银行缩写异常=============" + e.getMessage());
            return CommonsUtil.returnError("根据银行名称获取银行缩写失败！"+e.getMessage());
        }
    }

    /**
     * 根据userId查询用户贷记卡UserBankInfo
     *
     * @param userId
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/find/nature")
    public @ResponseBody
    Object findBankNatureByUserId(@RequestParam(value = "userId") long userId) {
        try {
            List<UserBankInfo> userBankInfos = userBankInfoBusiness.findLikeCardTypeByUserId(userId);
            if (userBankInfos == null || userBankInfos.size() < 1) {
                return CommonsUtil.returnError(CommonConstants.FALIED, "查询不到该用户相关贷记卡");
            } else {
                return CommonsUtil.returnSuccess(userBankInfos);
            }
        } catch (Exception e) {
            LOG.info("UserBankInfoService.findBankNatureByUserId, 查询用户贷记卡异常======" + e.getMessage());
            return CommonsUtil.returnError(CommonConstants.FALIED, "查询用户贷记卡失败！"+e.getMessage());
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/find/bankphone")
    public @ResponseBody
    Object findBankPhoneByUserIdAndBankNo(@RequestParam(value = "userId") long userId,
                                          @RequestParam(value = "cardNo") String cardNo) {
        try {
            List<UserBankInfo> userBankInfos = userBankInfoBusiness.findUserBankInfoByUseridAndCardno(userId, cardNo);

            if (ObjectUtils.isEmpty(userBankInfos)) {
                return CommonsUtil.returnError(CommonConstants.FALIED, "查询不到手机号记录");
            } else {
                return CommonsUtil.returnSuccess(userBankInfos.get(0));
            }
        } catch (Exception e) {
            LOG.error("UserBankInfoService.findBankPhoneByUserIdAndBankNo, 查询数据异常======" + e.getMessage());
            return CommonsUtil.returnError(CommonConstants.ERROR_PARAM, "查询数据失败！"+e.getMessage());
        }
    }

    /**
     * 截取银行支行名
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/find/bybankIntercept")
    public @ResponseBody
    Object queryBankNumberByBankName(@RequestParam(value = "card_no") String cardNo,
                                     @RequestParam(value = "bankbranch_name", required = false) String bankbranchName) {
        List list = new ArrayList();
        try {

            //判断支行名是否为空
            if (StringUtils.isBlank(bankbranchName)) {
                return CommonsUtil.returnError(CommonConstants.ERROR_PARAM, "支行信息不存在");
                //支行名为空
            } else {
                //根据支行名和银行卡号查询获取用户银行卡信息
                UserBankInfo bankInfo = userBankInfoBusiness.findBankNumberBybankbranchname(bankbranchName, cardNo);
                //获取支行名
                bankbranchName = bankInfo.getBankBranchName();
                //判断支行是中国银行执行
                if (bankbranchName.equals("中国银行")) {
                    list.add(0, bankInfo.getId());
                    list.add(1, bankInfo.getUserId());
                    list.add(2, bankInfo.getBankBranchName());
                    //判断不是中国银行执行
                } else {
                    //支行名是包含中国
                    if (bankbranchName.contains("中国")) {
                        //支行名包含中国银行
                        if (bankbranchName.contains("中国银行")) {
                            int Front = bankbranchName.indexOf("中国");
                            int after = bankbranchName.indexOf("银行");
                            bankbranchName = bankbranchName.substring(0, after + 2);
                            list.add(0, bankInfo.getId());
                            list.add(1, bankInfo.getUserId());
                            list.add(2, bankbranchName);
                            //支行名不包含中国银行
                        } else {
                            int Front = bankbranchName.indexOf("中国");
                            int after = bankbranchName.indexOf("银行");
                            bankbranchName = bankbranchName.substring(Front + 2, after + 2);
                            list.add(0, bankInfo.getId());
                            list.add(1, bankInfo.getUserId());
                            list.add(2, bankbranchName);
                        }
                        //支行名包含银行
                    } else if (bankbranchName.contains("银行")) {
                        //支行名包含浦发银行或者广发银行
                        if (bankbranchName.contains("浦发银行") || bankbranchName.contains("广发银行") || bankbranchName.contains("邮储银行")) {
                            //支行名包含浦发银行
                            if (bankbranchName.contains("浦发银行")) {
                                bankInfo.setBankBranchName("浦东发展银行");
                                list.add(0, bankInfo.getId());
                                list.add(1, bankInfo.getUserId());
                                list.add(2, bankInfo.getBankBranchName());
                                //支行名包含广发银行
                            }
                            if (bankbranchName.contains("广发银行")) {
                                bankInfo.setBankBranchName("广东发展银行");
                                list.add(0, bankInfo.getId());
                                list.add(1, bankInfo.getUserId());
                                list.add(2, bankInfo.getBankBranchName());
                            }
                            //支行名包含邮储银行
                            if (bankbranchName.contains("邮储银行")) {
                                bankInfo.setBankBranchName("邮政储蓄银行");
                                list.add(0, bankInfo.getId());
                                list.add(1, bankInfo.getUserId());
                                list.add(2, bankInfo.getBankBranchName());
                            }
                            //支行名不包含浦发和广发和邮储
                        } else {
                            int after = bankbranchName.indexOf("银行");
                            bankbranchName = bankbranchName.substring(0, after + 2);
                            list.add(0, bankInfo.getId());
                            list.add(1, bankInfo.getUserId());
                            list.add(2, bankbranchName);
                        }
                        //支行名不包含中国和银行
                    } else {
                        list.add(0, bankInfo.getId());
                        list.add(1, bankInfo.getUserId());
                        list.add(2, bankInfo.getBankBranchName());
                    }
                }
            }
            return CommonsUtil.returnSuccess(list);
        } catch (Exception e) {
            LOG.error("UserBankInfoService.queryBankNumberByBankName, 截取银行支行名异常=======" + e);
            return CommonsUtil.returnError("截取银行支行名失败！");
        }
    }

    //	根据userId和卡号验证是否是可用的指定类型的卡
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/verify/isuseable")
    public @ResponseBody
    Object verifyBankCard(@RequestParam(value = "userId") String userIdStr,
                          @RequestParam(value = "bankCardNumber") String bankCardNumber,
                          //卡类型,1为信用卡,0为储蓄卡
                          @RequestParam(value = "cardType", required = false, defaultValue = CommonConstants.DEBIT_2) String cardType) {
        try {
            UserBankInfo userBankInfo = userBankInfoBusiness.query(Long.valueOf(userIdStr), bankCardNumber);
            if (userBankInfo != null) {
                return CommonsUtil.returnSuccess(userBankInfo);
            } else {
                return CommonsUtil.returnError(CommonConstants.FALIED, "验证失败,该卡不可用,请更换!");
            }
        } catch (Exception e) {
            LOG.error("验证是否是可用的指定类型的卡异常========" + e);
            return CommonsUtil.returnError("验证是否是可用的指定类型的卡失败！");
        }
    }

    /**
     * 验证信用卡是否填写有效期和安全码
     *
     * @param userId
     * @param creditCardNumber
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/verify/cecuritycode/expiredtime")
    public @ResponseBody
    Object verifyCreditCard(@RequestParam(value = "userId") String userId,
                            @RequestParam(value = "creditCardNumber") String creditCardNumber) throws Exception {
        Map<String, String> verifyStringFiledIsNull = AuthorizationHandle.verifyStringFiledIsNull(userId, creditCardNumber);
        if (!CommonConstants.SUCCESS.equals(verifyStringFiledIsNull.get(CommonConstants.RESP_CODE))) {
            return verifyStringFiledIsNull;
        }
        UserBankInfo userBankInfo = userBankInfoBusiness.findUserBankInfoByUserIdAndCardNoAndState(Long.valueOf(userId), creditCardNumber, "0", "0");
        if (userBankInfo == null) {
            return CommonsUtil.returnError(CommonConstants.FALIED, "无该卡数据!");
        }

        String securityCode = userBankInfo.getSecurityCode();
        String expiredTime = userBankInfo.getExpiredTime();
        verifyStringFiledIsNull = AuthorizationHandle.verifyStringFiledIsNull(securityCode, expiredTime);
        if (!CommonConstants.SUCCESS.equals(verifyStringFiledIsNull.get(CommonConstants.RESP_CODE))) {
            return verifyStringFiledIsNull;
        }
        return CommonsUtil.returnSuccess(userBankInfo);
    }
    //设置账单日
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/set/bankinfo")
    public @ResponseBody
    Object setBankCardInfo(HttpServletRequest request,
                           @RequestParam(value = "userId") String userId,
                           @RequestParam(value = "bankCardNumber") String bankCardNumber,
                           @RequestParam(value = "securityCode") String securityCode,
                           @RequestParam(value = "expiredTime") String expiredTime,
                           @RequestParam(value = "billDay") String billDayStr,
                           @RequestParam(value = "repaymentDay") String repaymentDayStr,
                           @RequestParam(value = "creditBlance") String creditBlanceStr
    ) {
        Map<String, String> verifyStringFiledIsNull = AuthorizationHandle.verifyStringFiledIsNull(userId, bankCardNumber, securityCode, expiredTime, billDayStr, repaymentDayStr, creditBlanceStr);
        if (!CommonConstants.SUCCESS.equals(verifyStringFiledIsNull.get(CommonConstants.RESP_CODE))) {
            return verifyStringFiledIsNull;
        }

        Map<String, Object> verifyMoney = AuthorizationHandle.verifyMoney(creditBlanceStr, 2, BigDecimal.ROUND_HALF_UP);
        if (!CommonConstants.SUCCESS.equals(verifyMoney.get(CommonConstants.RESP_CODE))) {
            return verifyMoney;
        }

        UserBankInfo userBankInfo = userBankInfoBusiness.findUserBankInfoByUserIdAndCardNoAndState(Long.valueOf(userId), bankCardNumber, "0", "0");
        if (userBankInfo == null) {
            return CommonsUtil.returnError("无该卡数据,请先添加银行卡!");
        }

        BigDecimal creditBlance = new BigDecimal(creditBlanceStr);
        int billDate = 0;
        int repaymentDate = 0;

        if (billDayStr != null && !"".equals(billDayStr)) {
            try {
                billDate = Integer.valueOf(billDayStr);
            } catch (NumberFormatException e) {
                return CommonsUtil.returnError("输入日期格式非法,请重新输入");
            }
            if (!(billDate > 0 && billDate < 32)) {
                return CommonsUtil.returnError("输入日期格式非法,请重新输入");
            }
        }

        if (repaymentDayStr != null && !"".equals(repaymentDayStr)) {
            try {
                repaymentDate = Integer.valueOf(repaymentDayStr);
            } catch (Exception e) {
                return CommonsUtil.returnError("输入日期格式非法,请重新输入");
            }
            if (!(repaymentDate > 0 && repaymentDate < 32)) {
                return CommonsUtil.returnError("输入日期格式非法,请重新输入");
            }
        }

        userBankInfo.setSecurityCode(securityCode);
        userBankInfo.setExpiredTime(expiredTime);
        userBankInfo.setBillDay(billDate);
        userBankInfo.setRepaymentDay(repaymentDate);
        userBankInfo.setCreditBlance(creditBlance);
        userBankInfo = userBankInfoBusiness.saveUserBankInfo(userBankInfo);
        return CommonsUtil.returnSuccess(userBankInfo, "修改成功!");
    }

    /**
     * 获取用户所有借记卡信息
     * @param token
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/bank/getAllDebitCard/{token}")
    public @ResponseBody Object getAllDebitCard(@PathVariable(value = "token") String token,
                                                @RequestParam(value = "channelTag") String channelTag) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token异常！");
        }
        try {
            List<UserBankInfo> creditList = userBankInfoBusiness.getAvailBankCardList(userId, channelTag, CommonConstants.CREDIT_CARD);
            //List<UserBankInfo> debateList = userBankInfoBusiness.getAvailBankCardList(userId, channelTag, CommonConstants.DEBIT_CARD);
//            UserBankInfo defBankInfo = userBankInfoBusiness.queryDefBankInfoByUserid(userId);
//            boolean defDebateCard = false;
//            if (null != defBankInfo) {
//                defDebateCard = true;
//            }

//            boolean haveDebateCard = false;
//            if (creditList != null && creditList.size() > 0) {
//                haveDebateCard = true;
//            }

            LOG.info("/v1.0/user/bank/getAllDebitCard/{token}获取用户所有有效借记卡信息 userId = " + userId + "，resultJ = " + creditList.toString());

            Map map = CommonsUtil.returnSuccess(creditList, "查询成功！");
            map.put("haveDebateCard", true);
//            map.put("defDebateCard", defDebateCard);
            return map;
        } catch (Exception e) {
            LOG.error("/v1.0/user/bank/getAllDebitCard/{token}获取用户所有有效借记卡信息 userId = " + userId + "异常" + e.getMessage());
            e.printStackTrace();
            if ("无可用银行卡！".equals(e.getMessage())) {
                return CommonsUtil.returnError(e.getMessage());
            }
             if (e.getMessage().contains("不支持")) {
                return CommonsUtil.returnError(e.getMessage());
             }
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 查询银行卡支持通道
     * @param bankAbbr
     * @param channelId
     * @return
     */
    @GetMapping(value = "/v1.0/user/bank/supportChannel")
    public @ResponseBody Object supportChannel(@RequestParam(value = "bankAbbr") String bankAbbr,
                                               @RequestParam(value = "channelId") String channelId) {
        try {
            Boolean supportChannel = userBankInfoBusiness.supportChannel(bankAbbr, channelId);
            return CommonsUtil.returnSuccess(supportChannel, "成功！");
        } catch (Exception e) {
            if (e.getMessage().contains("查询失败")) {
                return CommonsUtil.returnError(e.getMessage());
            }
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 根据userId获取用户的所有银行卡
     * @param userId
     * @return
     */
    @GetMapping(value = "/v1.0/user/bank/getBindBankInfoByUserId")
    public @ResponseBody Object getBindBankInfoByUserId(@RequestParam("userId") long userId) {
        try {
            List<Map<String, Object>> list = userBankInfoBusiness.getBindBankInfoByUserId(userId);
            if (null == list) {
                return CommonsUtil.returnError("无法修改商户结算卡信息，该商户还未绑定任何银行卡！");
            }
            return CommonsUtil.returnSuccess(list, "查询成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }
}
